<template>
  <div class="containerWrap">
    <el-container class="container">
      <el-aside class="appTree" width="200px">
      <app-tree v-bind:tree-data="treeData"
                v-on:appTreeClick="treeClickHandle" title="受理单位"></app-tree>
    </el-aside>
      <el-main class="rightMain">
        <el-container>
          <el-header class="dzy-main-header">
            <div class="btn-group-el">
              <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
            </div>
             <div class="dzy-custom-search-box">
              <div>
                姓名：<el-input size="small" placeholder="请输入姓名" v-model="queryData.name" clearable class="dzy-custom-input"></el-input>
              </div>
               <div>
                手机：<el-input size="small" placeholder="请输入手机" v-model="queryData.phone" clearable class="dzy-custom-input"></el-input>
              </div>
              <div>
                所属单位：<el-input size="small" placeholder="请输入所属单位" v-model="queryData.courtName" clearable class="dzy-custom-input"></el-input>
              </div>
              <div>
                <el-button size="small" @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
              </div>
            </div>
          </el-header>
          <el-main class="tableMain">
            <app-table :page-data="pageData"
                       :table-columns="tableColumns"
                       v-on:handleCheckedRows="handleCheckedRows"
                       v-on:currentChange="handleCurrentChange"/>
            <el-dialog :title="dialogTitle"
                       :visible.sync="dialogFormVisible"
                       :close-on-click-modal="false"
                       class="dialog_style"
                        :before-close="close">
              <div class="formWrapper">
                <el-form :model="formData"
                         :rules="rules"
                         ref="formData"
                         label-width="90px"
                         size="small">
                  <el-divider content-position="left">基本信息</el-divider>
                  <el-row :gutter="15">
                    <el-col :span="24">
                      <el-row :gutter="0">
                      <el-col :span="18">
                        <el-col :span="24">
                          <el-form-item label="姓名：" prop="name">
                            <el-input placeholder="姓名" v-model="formData.name"></el-input>
                          </el-form-item>
                        </el-col>
                        <el-col :span="24">
                          <el-form-item label="所属单位：" prop="courtName">
                            <el-input placeholder="所属单位" @focus="handleSelectUser" v-model="formData.courtName"></el-input>
                          </el-form-item>
                        </el-col>
                        <el-col :span="24">
                          <el-form-item label="性别：" prop="sex">
                            <el-select filterable style="width: 100%;" clearable v-model="formData.sex" placeholder="性别">
                              <el-option v-for="item in genderOption"
                                :key="item.id"
                                :value="item.value"
                                :label="item.name"></el-option>
                            </el-select>
                          </el-form-item>
                        </el-col>
                        <el-col :span="24">
                          <el-form-item label="手机：" prop="phone">
                            <el-input placeholder="手机" v-model="formData.phone"></el-input>
                          </el-form-item>
                        </el-col>
                      </el-col>
                      <el-col :span="6">
                        <el-col :span="24">
                          <el-form-item label-width='20px'>
                            <app-upload ref="appUpload"
                                        v-model="formData.photo"></app-upload>
                          </el-form-item>
                        </el-col>
                      </el-col>
                      </el-row>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="职务：" prop="position">
                        <el-select filterable style="width: 100%;" clearable v-model="formData.position" placeholder="职务">
                              <el-option v-for="item in jobOption"
                                :key="item.id"
                                :value="item.value"
                                :label="item.name"></el-option>
                            </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="办公电话：" prop="officePhone">
                        <el-input placeholder="办公电话" v-model="formData.officePhone"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="办公地址：" prop="officeAddress">
                        <el-input placeholder="办公地址" v-model="formData.officeAddress"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </div>
              <div v-if="!showOnly" slot="footer" class="dialog-footer">
                <el-button @click="cancel('formData')">取 消</el-button>
                <el-button type="primary" @click="save('formData')">提 交</el-button>
              </div>
            </el-dialog>
            <!-- 系统用户 start -->
            <el-dialog title="系统用户" :visible.sync="dialogUserVisible" :before-close="closeUser" class="dialog_style">
              <el-table :data="usersData"
                :header-cell-style="{backgroundColor:'#399FFB', color: '#fff'}"
                highlight-current-row
                @current-change="handleRowClick">
                <el-table-column v-for="(item, index) in UsersColumns"
                  :key="index"
                  :prop="item.prop"
                  :label="item.label"
                  :formatter="item.formatter"
                  :show-overflow-tooltip="true">
                </el-table-column>
              </el-table>
              <div style="width:100%;height:20px"></div>
              <el-pagination background
                @current-change="handleCurrentUserChange"
                :current-page.sync="currentPage"
                :page-size="!usersPage.limit ? 10 : usersPage.limit"
                layout="total, prev, pager, next, jumper"
                :total="usersPage.total">
              </el-pagination>
              <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="closeUser">取 消</el-button>
                <el-button size="small" @click="sureUser" type="primary">确 定</el-button>
              </div>
            </el-dialog>
            <!-- 系统用户 end -->
          </el-main>
        </el-container>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import AppUpload from '@/components/AppAvatarUpload'
import BtnGroup from '@/components/BtnGroup'
import AppTable from '@/components/AppTable'
import {getDictDataOption} from '@/utils/getDictDataOption'
import {
  createLawJudge,
  findLawJudge,
  updateLawJudge,
  deleteLawJudge,
  getLawJudge,
  findLawCourt,
  findAllLawCourt
} from '@/http/kehuApi'
export default {
  data () {
    return {
      currentPage: 1,
      dialogTitle: '',
      dialogFormVisible: false,
      dialogUserVisible: false,
      treeData: [],
      usersData: [],
      genderOption: [],
      jobOption: [],
      cbunitOption: [],
      currentSelectedData: [],
      pageData: {},
      queryData: {},
      usersPage: {},
      formData: {},
      queryUsersData: {},
      currentUserData: {},
      showOnly: false,
      tableColumns: [
        { label: '姓名', prop: 'name' },
        { label: '所属单位', prop: 'courtName' },
        { label: '性别', prop: 'sex', formatter: this.sexFormatter },
        { label: '手机', prop: 'phone' },
        { label: '创建时间', prop: 'createTime', formatter: this.dateFormatter },
        { label: '备注', prop: 'remark' }
      ],
      UsersColumns: [
        { label: '单位名称', prop: 'name' },
        { label: '单位类型', prop: 'type', formatter: this.typeFormatter },
        { label: '层级', prop: 'level' },
        { label: '地址', prop: 'address' }
      ],
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        courtId: [{ required: true, message: '请选择所属单位', trigger: 'change' }]
      },
      dataPickerBeforeTodayOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      }
    }
  },
  mounted () {
    this.getTableData()
    this.getTreeData()
    this.genderOption = getDictDataOption('性别')
    this.cbunitOption = getDictDataOption('受理单位类型')
    this.jobOption = getDictDataOption('职位名称')
  },
  components: {
    AppTree,
    BtnGroup,
    AppTable,
    AppUpload},
  methods: {
    // 时间格式化
    dateFormatter (row) {
      if (row && row.createTime) {
        return this.$moment(row.createTime).format('YYYY-MM-DD')
      }
    },
    sexFormatter (row) {
      let name = ''
      for (let index = 0; index < this.genderOption.length; index++) {
        const element = this.genderOption[index]
        if (row.sex === element.value) {
          name = element.name
        }
      }
      return name
    },
    typeFormatter (row) {
      let name = ''
      for (let index = 0; index < this.cbunitOption.length; index++) {
        const element = this.cbunitOption[index]
        if (row.type === element.value) {
          name = element.name
        }
      }
      return name
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        if (callbackData.btnType === 'post') {
          this.formData = this.formData.courId ? this.formData : {}
        } else {
          let data = callbackData.rows[0]
          this.getSingle(data)
        }
        this.showOnly = callbackData.showOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
      }
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$alert('请填写正确表单格式', '', {
            confirmButtonText: '确定'
          })
          return ''
        } else {
          if (this.formData.id) {
            updateLawJudge(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.cancel(formName)
                this.$message({
                  showClose: true,
                  message: '修改成功',
                  type: 'success'
                })
              }
            })
          } else {
            console.log(this.formData)
            createLawJudge(this.formData).then(resp => {
              if (resp.data && resp.code === '200') {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.cancel(formName)
                this.getTableData()
              }
            })
          }
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deleteLawJudge(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.$message({
                  showClose: true,
                  message: '删除成功',
                  type: 'success'
                })
              }
            })
          })
        })
      }
    },
    cancel (formName) {
      this.formData = {}
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    close () {
      this.formData = {}
      this.dialogFormVisible = false
    },
    getTableData () {
      let param = this.queryData
      findLawJudge(param).then(resp => {
        if (resp.data && resp.code === '200') {
          this.pageData = resp.data
        }
      })
    },
    getUserTable () {
      let param = this.queryUsersData
      findLawCourt(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.usersPage = data
            this.usersData = data.items
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
          return ''
        }
      })
    },
    getTreeData () {
      findAllLawCourt().then(resp => {
        if (resp.code && resp.code === '200') {
          this.treeData = resp.data
        }
      })
    },
    // 搜索按钮操作
    searchHandleClick () {
      this.queryData.offset = 0
      this.getTableData()
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
      } else {
        this.currentSelectedData = []
      }
    },
    handleCurrentChange (val) {
      this.queryData.offset = (val - 1) * 10
      this.getTableData()
    },
    handleCurrentUserChange (val) {
      this.queryUsersData.offset = (val - 1) * 10
      this.getUserTable()
    },
    // 查看单条活动分类详细信息
    getSingle (data) {
      getLawJudge(data).then(resp => {
        if (resp.data && resp.code === '200') {
          this.formData = resp.data
        }
      })
    },
    treeClickHandle (data) {
      this.queryData = {}
      this.queryData.lawCourtId = data.id
      this.$set(this.formData, 'courtName', data.name)
      this.$set(this.formData, 'courtId', data.id)
      this.getTableData()
    },
    handleSelectUser () {
      this.dialogUserVisible = true
      this.getUserTable()
    },
    handleRowClick (rows) { // 单行点击事件
      console.log(rows)
      this.currentUserData = rows
    },
    sureUser () {
      if (JSON.stringify(this.currentUserData) !== '{}') {
        this.$set(this.formData, 'courtId', this.currentUserData.id)
        this.$set(this.formData, 'courtName', this.currentUserData.name)
        this.dialogUserVisible = false
      } else {
        this.$message({
          type: 'info',
          message: '请选择单位'
        })
      }
    },
    closeUser () {
      this.dialogUserVisible = false
    }
  }
}
</script>
<style scoped>
  .containerWrap {
    padding:10px;
    height: 100%;
    box-sizing: border-box
  }
  .container {
    height: 100%;
  }
</style>
